package com.lm.factory;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lm.enums.DistributedLockTypeEnum;
import com.lm.lock.RedisDistributedLock;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;

/**
 * 分布式锁工厂
 * @author LM
 * @date 2025/2/7 22:13
 */
@Component
public class DistributedLockFactory {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private String uuidValue;

    public DistributedLockFactory() {
        this.uuidValue = IdUtil.simpleUUID();
    }

    public Lock getDistributedLock(String lockKey,String lockName) {
        if(StrUtil.isEmpty(lockKey)) {
            throw new RuntimeException("lockKey 不能为空");
        }
        Lock lock = null;
        switch (DistributedLockTypeEnum.getEnumByValue(lockKey)){
            case REDIS:
                lock = new RedisDistributedLock(stringRedisTemplate, lockName, uuidValue+":"+Thread.currentThread().getId());
            case MYSQL:
            case ZOOKEEPER:
            default:
        }
        if(ObjectUtil.isNull(lockKey)){
            throw new RuntimeException("未获取到有效的分布式锁");
        }
        return lock;
    }
}
